<!-- src/views/Item/AddItem.vue -->
<template>
  <div class="add-item">
    <h2>新增商品</h2>
    <el-form :model="form" label-width="100px" @submit.prevent="submitForm">
      <el-form-item label="名称" required>
        <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="form.description" type="textarea" placeholder="请输入商品描述"></el-input>
      </el-form-item>
      <el-form-item label="价格" required>
        <el-input-number v-model="form.price" :min="0" :precision="2" placeholder="0.00"></el-input-number>
      </el-form-item>
      <el-form-item label="库存" required>
        <el-input-number v-model="form.stock" :min="0"></el-input-number>
      </el-form-item>
      <!-- 可选：状态 -->
      <!-- <el-form-item label="状态">
        <el-switch v-model="form.status" active-value="1" inactive-value="0"></el-switch>
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" native-type="submit" :loading="loading">提交</el-button>
        <el-button @click="$router.back()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { itemApi } from '@/api/itemApi' // 确保你有这个 API 封装

const router = useRouter()
const loading = ref(false)

const form = reactive({
  name: '',
  description: '',
  price: 0,
  stock: 0,
  status: 1 // 默认上架
})

const submitForm = async () => {
  // 简单校验
  if (!form.name || !form.price || !form.stock) {
    ElMessage.warning('请填写必填项')
    return
  }

  try {
    loading.value = true
    await itemApi.addItem(form)
    loading.value = false

    ElMessage.success('商品添加成功！')

    // 提示后跳转回商品列表
    ElMessageBox.confirm('商品添加成功，是否返回商品列表？', '提示', {
      type: 'success',
      confirmButtonText: '返回列表',
      cancelButtonText: '继续添加'
    }).then(() => {
      router.push('/items') // 返回列表
    }).catch(() => {
      // 继续添加：清空表单
      Object.assign(form, {
        name: '',
        description: '',
        price: 0,
        stock: 0
      })
    })
  } catch (error) {
    loading.value = false
    console.error('添加商品失败:', error)
    ElMessage.error('添加失败，请检查网络或输入内容')
  }
}
</script>

<style scoped>
.add-item {
  padding: 20px;
  max-width: 600px;
}
</style>
